import { DATA_TYPE_NUMBER, DATA_TYPE_BOOLEAN, IS_EXEC_CONDITION, STRATEGY_MODE } from '../constant';
import { validateActions } from 'src/components/Actions/validate';

/**  获取普通策略最终的配置信息
 * @param {Object}} values
 * @param {String} actionType 如果为copy,则需要把rule_id去掉
 */
export function getCommonFinallyConfig(values, actionType, strategyConfig, errCallback) {
  const finallyConfig = {};
  const mode = {
    code: values.strategy_mode,
  };
  try {
    // 判断是否有执行条件
    // 如果有执行条件，则验证必填情况
    if (values.is_exec_condition === IS_EXEC_CONDITION._TRUE) {
      finallyConfig.condition_groups = getConditionGroupJson(strategyConfig.condition_groups);
    }

    // 判断是否有阈值条件
    // 如果有，则验证必填情况
    if (values.strategy_mode === STRATEGY_MODE._WEIGHT || values.strategy_mode === STRATEGY_MODE._SCORE_CARD) {
      mode.hit_handle_by_threshold = getHitHandleByThreshold(strategyConfig.mode.hit_handle_by_threshold);
    }

    // 判断是否有rules条件
    // 如果有，则验证必填情况
    if (values.strategy_mode) {
      if (values.strategy_mode !== STRATEGY_MODE._SCORE_CARD) {
        mode.rules = Object.assign(
          [],
          getRules(strategyConfig.mode.rules, STRATEGY_MODE, values.strategy_mode, actionType)
        );
        // 是否有评分卡
      } else {
        mode.rules = Object.assign([], getRulesScore(strategyConfig.mode.score_rules, actionType));
      }
    }

    // 如果为自定义规则
    if (values.strategy_mode === STRATEGY_MODE._CUSTOM) {
      mode.hit_handle_by_expression = {
        expression: values.expression,
        descr: values.descr || '',
        hit_handle: values.hit_handle,
      };
    }

    finallyConfig.mode = mode;
    return finallyConfig;
  } catch (err) {
    errCallback(err);
    return false;
  } finally {
    console.log('heh');
  }
}

/**
 * @method getConditionGroupJson
 * @description 获取条件组json
 */
export function getConditionGroupJson(data) {
  if (!data || (data && data.length === 0)) {
    throw '请配置条件组';
  }
  data.forEach((item) => {
    if (!item.junction_type) {
      throw '请设置联合条件';
    }
    if (item.conditions.length === 0) {
      throw '请配置条件';
    }
    item.conditions.forEach((item) => {
      if (!item.junction_type) {
        throw '请设置规则';
      }
      if (!item.left_var_code || !item.left_var_type) {
        throw '请设置条件左变量';
      }
      if (!item.operator) {
        throw '请选择条件操作符';
      }
      // item.operator = getOperator(item.operator);
      // if (item.operator.type !== 1) {
      //   if (item.right_var_code === undefined || item.right_var_code === '' || !item.right_var_type) {
      //     throw '请设置条件右变量';
      //   }
      //   delete item.isFocus;
      // } else {
      //   delete item.right_var_code;
      //   delete item.right_var_name;
      //   delete item.right_var_type;
      // }
    });
  });
  return data;
}

/**
 * @method getCondition
 * @description 获取条件json
 */
export function getCondition(value) {
  if (!value.junction_type) {
    throw '请设置规则';
  }
  if (!value.left_var_code || !value.left_var_type) {
    throw '请设置条件左变量';
  }
  // if (value.operator && value.operator.type !== 1) {
  //   if (value.right_var_code === undefined || value.right_var_code === '' || !value.right_var_type) {
  //     throw '请设置条件右变量';
  //   }
  // } else {
  //   delete value.right_var_code;
  //   delete value.right_var_name;
  //   delete value.right_var_type;
  // }
  delete value.isFocus;
  // value.operator = getOperator(value.operator);
  if (!value.operator) {
    throw '请选择条件操作符';
  }
  return value;
}

/**
 * @method getOperator
 * @description 获取操作符json
 */
export function getOperator(value) {
  if (!value) {
    throw '请选择条件操作符';
  }
  if (Object.keys(value).length === 0) {
    throw '请选择条件操作符';
  }
  if (!value.operator || !value.symbol) {
    throw '请选择条件操作符';
  }
  return value;
}

/**
 * @method getHitHandleByThreshold
 * @description 获取阈值的json
 */
export function getHitHandleByThreshold(value) {
  if (
    value.first_threshold === undefined ||
    value.second_threshold === undefined ||
    value.threshold_operators.length === 0 ||
    value.hit_handles.length === 0
  ) {
    throw '请设置阈值';
  }
  return value;
}

/**
 * @method getHitHandleByExpression
 * @description 获取自定义表达式的json
 */
export function getHitHandleByExpression(value) {
  return value;
}

/**
 * @method getRules
 * @description 获取规则的json
 * @param STRATEGY_MODE 码表 对action的判断不一样
 * @param mode 模式，对action的判断不一样
 * @param actionType copy类型需要去掉rule_id
 */
export function getRules(value, STRATEGY_MODE, mode, actionType) {
  if (value.length === 0) {
    throw '请设置规则';
  }
  value.forEach((item, index) => {
    if (item.name) {
      if (!/^[\u4E00-\u9FA5_a-zA-Z0-9]+$/.test(item.name)) {
        throw '规则名限中英文数字下划线';
      }
      if (item.name.length > 128) {
        throw '规则名称最长为128个字符';
      }
    }
    if (Object.keys(item.condition).length > 0) {
      item.condition = getCondition(item.condition);
    } else {
      throw '请设置规则';
    }

    // 如果为风险权重
    if (STRATEGY_MODE._WEIGHT === mode) {
      if (
        !item.actions ||
        (item.actions && (typeof item.actions === 'string' || Object.keys(item.actions).length === 0))
      ) {
        throw '请设置计算权重';
      }
    }
    // 如果为自定义
    if (STRATEGY_MODE._CUSTOM === mode) {
      delete item.action;
    }
    if (actionType === 'copy') {
      delete item.rule_id;
    }
  });
  return value;
}

/**
 * @method validateRuleItem
 * @description 验证ruleset 的规则
 */
export function validateRuleItem(value, mode) {
  if (Object.keys(value.condition).length > 0) {
    value.condition.conditions.forEach((it) => {
      getCondition(it);
    });
  } else {
    throw '请设置条件';
  }
  value.condition_actions = validateActionsConfig(value.condition_actions, mode);
  return value;
}

/**
 * @method getRulesSet
 * @description 获取决策集规则的json
 * @param actionType copy类型需要去掉rule_id
 */
export function getRulesSet(value, actionType, mode) {
  if (!value.execute_mode) {
    throw '请设置执行模式';
  }
  if (value.express_rules.length === 0) {
    throw '请设置规则';
  }
  value.express_rules.forEach((item, index) => {
    if (item.name) {
      if (!/^[\u4E00-\u9FA5_a-zA-Z0-9]+$/.test(item.name)) {
        throw '规则名限中英文数字下划线';
      }
      if (item.name.length > 128) {
        throw '规则名称最长为128个字符';
      }
    } else {
      throw '请设置规则名称';
    }
    if (item.code) {
      if (!/^[a-zA-Z][_a-zA-Z0-9]*$/.test(item.code)) {
        throw '规则CODE限英文数字下划线，并以英文开头';
      }
      if (item.code.length > 128) {
        throw '规则名称最长为128个字符';
      }
    } else {
      throw '请设置规则CODE';
    }
    if (Object.keys(item.condition).length > 0) {
      item.condition.conditions.forEach((it) => {
        getCondition(it);
      });
    } else {
      throw '请设置条件';
    }

    if (actionType === 'copy') {
      delete item.rule_id;
    }
    item.condition_actions = validateActionsConfig(item.condition_actions, mode);
    // item.condition_express = validateConditionExpress(item.condition_express, item.conditions);
  });

  // console.log(value);
  return value;
}

function validateConditionExpress(value, rules) {
  // console.log(value, rules);
  if (value) {
    const reg = /^[0-9(]([|]{2}|[&]{2}|[0-9()])*$/;
    const endReg = /[0-9)]$/;
    const errReg = /(\(&)|(\(\|)|(&\))|(\|\))|(\)\()|(\d\()|(\)\d)|(&\|)|(\|&)|(\(\))/;
    if (!reg.test(value) || !endReg.test(value) || errReg.test(value)) {
      throw '非法字符，请检查后重新输入1';
    }
    const lReg = /\(/g;
    const rReg = /\)/g;
    const lArr = value.match(lReg) || [];
    const rArr = value.match(rReg) || [];
    if (lArr.length !== rArr.length) {
      throw '非法字符，请检查后重新输入2';
    }

    const reg2 = /([|]{2}|[&]{2}|[()])/g;
    const newExpress = value.replace(reg2, '-');
    const arr = newExpress.split('-');
    arr.forEach((item) => {
      if (item && Number(item) > rules.length) {
        throw `条件表达式序号${item}不存在`;
      }
    });
  }
  return value;
}

/**
 * @method getRulesScore
 * @description 获取评分卡规则的json
 * @param actionType copy类型需要去掉rule_id
 */
export function getRulesScore(value, actionType) {
  if (value.length === 0) {
    throw '请设置规则';
  }
  value.forEach((item, index) => {
    if (item.name) {
      if (!/^[\u4E00-\u9FA5_a-zA-Z0-9]+$/.test(item.name)) {
        throw '规则名限中英文数字下划线';
      }
      if (item.name.length > 128) {
        throw '规则名称最长为128个字符';
      }
    }
    if (!item.left_var_code || !item.left_var_type) {
      throw '请设置变量名';
    }
    if (item.default_score === '') {
      throw '请设置默认分';
    }
    item.cases = getRulesScoreCase(item);
    if (actionType === 'copy') {
      delete item.rule_id;
    }
  });
  return value;
}

/**
 * @method getRulesScoreCase
 * @description 获取评分卡规则分箱的json
 */
export function getRulesScoreCase(value) {
  if (value.length < 2) {
    throw '请至少设置两个分箱';
  }
  value.cases.forEach((item, index) => {
    // 如果是数值，则判断min,max
    if (
      DATA_TYPE_NUMBER.includes(value.left_var_data_type) ||
      value.left_var_data_type === null ||
      value.left_var_data_type === undefined
    ) {
      if (!item.conditions || item.conditions.length === 0) {
        throw '请设置分箱区间值';
      }
    }
    // 如果是boolean，则判断min,max
    if (DATA_TYPE_BOOLEAN.includes(value.left_var_data_type)) {
      if (item.value === undefined || item.value === null) {
        throw '请设置分箱区间值';
      }
    }

    if (!item.score && item.score !== 0) {
      throw '请设置分值';
    }
  });
  return value.cases;
}

export function validateChallenge(data, errorCallback) {
  const total = data.nodes.reduce((total, it) => {
    total += it.percent || 0;
    return total;
  }, 0);
  if (total !== 100) {
    throw data.name + '节点的百分比总和必须等于100%';
  }
  data.nodes.forEach((item) => {
    if (item.strategy_mode === undefined || !item.strategy_id) {
      throw `请配置${data.name}节点下${item.name}的策略`;
    }
  });
}

/**
 * 验证动作配置
 */
export function validateActionsConfig(value, type) {
  switch (type) {
    //  决策集
    case STRATEGY_MODE._RULESET:
      // if (value.length !== 2) {
      //   throw '决策集的动作不正确，动作应该有且仅有两条';
      // }
      value.forEach((item) => {
        if (item.action_type !== 'condition_true' && item.action_type !== 'condition_false') {
          throw '决策集的动作不正确,必须是命中或者未命中状态';
        }
        item.actions.length > 0 && validateActions(item.actions);
      });
      break;
    //  风险权重
    case STRATEGY_MODE._WEIGHT:
      if (value.length === 0) {
        throw '请设置动作';
      }
      value.forEach((item) => {
        if (item.min === undefined || item.min === null) {
          throw '请设置权重区间最小值';
        }
        if (item.max === undefined || item.min === null) {
          throw '请设置权重区间最大值';
        }
        if (item.max <= item.min) {
          throw '请确保权重区间最大值大于权重区间最小值';
        }
        validateActions(item.actions);
      });
      break;
    //  评分卡
    case STRATEGY_MODE._SCORE_CARD:
      if (value.length === 0) {
        throw '请设置动作';
      }
      value.forEach((item) => {
        if (0 !== item.min && !item.min) {
          throw '请设置得分区间最小值';
        }
        if (0 !== item.max && !item.max) {
          throw '请设置得分区间最大值';
        }
        if (item.max <= item.min) {
          throw '请确保得分区间最大值大于得分区间最小值';
        }
        validateActions(item.actions);
      });
      break;
    default:
      break;
  }

  return value;
}
